//
//  NSString+Util.m
//  MobileCRM
//
//  Created by winter on 16/2/22.
//  Copyright © 2016年 江苏金恒信息科技有限公司. All rights reserved.
//

#import "NSString+Util.h"
#import "UIColor+Util.h"
#import "RSA.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation NSString(Util)

- (NSDate *)convertToDateWithFormatStr:(NSString *)formatStr
{
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:formatStr];
    return [format dateFromString:self];
}

- (NSString *)stringWithLocalizedFromTable:(NSString *)tbl withComment:(NSString *)comment
{
    NSString *localizedStr = NSLocalizedStringFromTable([self lowercaseString], tbl, comment);
    return [localizedStr isEqualToString:[self lowercaseString]] ? self : localizedStr;
}

- (BOOL)validateByRegEx:(NSString *)regexStr
{
    return [[NSPredicate predicateWithFormat:@"SELF MATCHES %@",regexStr] evaluateWithObject:self];
}

- (NSString *)wsStringByTrimmingWhiteSpace
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (UIColor *)wsStringConvertToUIColor
{
    return [UIColor colorWithHexString:self];
}
- (UIColor *)wsStringConvertToUIColorWithAlpha:(CGFloat)alpha
{
    return [UIColor colorWithHexStringWithAlpha:self alpha:alpha];
}

+ (NSString*)wsGenUUID
{
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    CFRelease(uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString*)uuid_string_ref];
    CFRelease(uuid_string_ref);
    CFRelease(uuid_ref);
    return uuid;
}

- (NSString *)aesCBCModelEncrypt:(NSString *)keyStr
{
    
    NSData *key = [keyStr dataUsingEncoding:NSUTF8StringEncoding];
    //NSData *key = hexToBytes(@"109dbaaf84eddd86173b270033d7b592");
    NSData *content = [self dataUsingEncoding:NSUTF8StringEncoding];
    
    size_t bufferSize = content.length + kCCBlockSizeAES128;
    void *buffer = malloc( bufferSize );
    size_t numBytesEncrypted = 0;
    
    CCCryptorStatus result;
    result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
                     kCCOptionECBMode | kCCOptionPKCS7Padding,
                     key.bytes, key.length,
                     NULL,
                     content.bytes, content.length,
                     buffer, bufferSize, &numBytesEncrypted);
    if(result == kCCSuccess)
    {
        NSData *data = [NSData
                        dataWithBytesNoCopy:buffer
                        length:numBytesEncrypted];
        return [self dataToHexString:data];
    }
    return nil;
}
- (NSData *)aesCBCModelDecryptForString:(NSString *)keyStr
{
    NSData *data = [self hexToBytes:self];
    NSData *key = [keyStr dataUsingEncoding:NSUTF8StringEncoding];
    
    size_t bufferSize = data.length + kCCBlockSizeAES128;
    void *buffer = malloc( bufferSize );
    size_t numBytesEncrypted = 0;
    
    CCCryptorStatus result;
    result = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                     kCCOptionECBMode | kCCOptionPKCS7Padding,
                     key.bytes, key.length,
                     NULL,
                     data.bytes, data.length,
                     buffer, bufferSize, &numBytesEncrypted);
    if(result == kCCSuccess)
    {
        
        
        NSData *data2 = [NSData
                         dataWithBytesNoCopy:buffer
                         length:numBytesEncrypted];
        //NSString *str = [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding];
        return data2;
    }
    return nil;
}


-(NSData*) hexToBytes:(NSString *)hex
{
    NSMutableData* data = [NSMutableData data];
    unsigned int idx, intValue;
    for (idx = 0; idx+2 <= hex.length; idx+=2) {
        NSString* hexStr = [hex substringWithRange:NSMakeRange(idx, 2)];
        NSScanner* scanner = [NSScanner scannerWithString:hexStr];
        [scanner scanHexInt:&intValue];
        [data appendBytes:&intValue length:1];
    }
    return data;
}
- (NSString *)dataToHexString:(NSData *)data
{
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}
@end
